<template>
  <div>
    <div id="map" class="map" />
    <el-tag class="tag">请绘制新的基地</el-tag>
  </div>
</template>

<script>
import mapinit from '@/utils/map-init.js'
export default {
  name: 'BaseMap',
  props: {
    location: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      zoom: '15',
      tool: null,
      map: null,
      T: null,
      drawFlag: false
    }
  },
  mounted() {
    setTimeout(() => {
      this.initMap()
    }, 1000)
  },
  methods: {
    initMap() {
      mapinit.init().then(T => {
        const map = new T.Map('map', {
          minZoom: 4
        })
        map.setMapType(TMAP_HYBRID_MAP)// 设置卫星路网复合地图
        map.centerAndZoom(new T.LngLat(this.location.lon, this.location.lat), this.zoom)// 根据基地经纬度定位

        this.T = T
        this.map = map

        const polygonTool = new T.PolygonTool(this.map, {
          color: '#009966',
          weight: 3,
          opacity: 1,
          fillColor: '#009966',
          fillOpacity: 0.3,
          showLabel: true
        })

        polygonTool.setTips('双击结束绘制')
        polygonTool.addEventListener('draw', (event) => {
          const polygon = event.currentPolygon
          this.$confirm('是否绘制完毕?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$emit('draw-over', event.currentLnglats)
          }).catch(() => {
            polygon.enableEdit()
            this.bindClick(polygon)
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
        })
        polygonTool.open()
        this.tool = polygonTool
      })
    },
    bindClick(polygon) {
      polygon.addEventListener('click', (event) => {
        this.$confirm('是否绘制完毕?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          event.target.disableEdit()
          this.$emit('draw-over', event.target.getLngLats())
        }).catch(() => {
          event.target.enableEdit()
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      })
    },
    addData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$emit('add-place')
        }
      })
    },
    cancel() {
      this.$emit('cancel-dialog')
      this.btnFlag = true
      this.tool.clear()
      this.tool.close()
    }
  }
}
</script>

<style scoped>

.map-wrapper {
  position: relative;
}

.map {
  width: 100%;
  height: calc( 100vh - 50px);
  z-index: 1;
  /* margin-top: 20px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 0 5px 0 #333; */
}

.btn {
  position: absolute;
  top: 60px;
  right: 10px;
  z-index: 2;
}

.tag {
  position: absolute;
  top: 60px;
  left: 10px;
  z-index: 2;
}

.map >>> .tdt-control-copyright {
  display: none;
}

</style>
